package com.jie.lipassword;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

import com.jie.lipassword.db.DbContect;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private RelativeLayout main_title;
    private ImageButton main_add;
    private EditText search_edit;
    private ImageView search_button;

    private ListView type_item_list;

    DbContect helper;
    private SQLiteDatabase db;

    private ArrayList<String> type_list_data = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //数据库实列化
        dbcontext();

    }

    @Override
    protected void onResume() {
        super.onResume();
        set_init();
        showList();
    }

    private void set_init() {
        main_title = findViewById(R.id.main_title);
        main_add = findViewById(R.id.main_add);
        type_item_list = findViewById(R.id.type_item_list);
        search_edit = findViewById(R.id.search_edit);
        search_button = findViewById(R.id.search_button);

        search_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                // 日志记录当前文本内容
                Log.i("afterTextChanged", editable.toString());

                // 检查编辑框是否为空
                String text = editable.toString(); // 将 Editable 转换为字符串并存储
                if (text.isEmpty()) { // 更推荐使用 isEmpty()
                    showList(); // 显示列表
                    return; // 结束方法
                }

                // 如果不为空，执行搜索逻辑
                search_type(text);
            }
        });

        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = String.valueOf(search_edit.getText()); // 将 Editable 转换为字符串并存储

                if (text.isEmpty()){
                    showList();
                    return;
                }else{
                    search_type(String.valueOf(search_edit.getText()));
                }
            }
        });

        FindTitle.setTitle(this,main_title,false,true,"密码管理器");

        main_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建一个意图，用于启动另一个页面
                Intent intent = new Intent(view.getContext(), AddActivity.class);
                startActivity(intent);
            }
        });
    }

    private void dbcontext(){
        helper = new DbContect(MainActivity.this);
        db = helper.getWritableDatabase();
    }

    private void search_type(String text){
        Cursor cursor = db.query("TypeTable",null,"type_name LIKE ?",new String[]{String.valueOf("%"+text+"%")},null,null,null);
        type_list_data = new ArrayList<>();

        while(cursor.moveToNext()) {
            @SuppressLint("Range") String type_name = cursor.getString(cursor.getColumnIndex("type_name"));
            type_list_data.add(type_name);
            Log.i("SearchMainactivity", "result: type_name: " + type_name);
        }
        // 关闭游标，释放资源
        cursor.close();
        List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < type_list_data.size(); i++) {
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("type_name", type_list_data.get(i));
            data.add(item);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.type_item, new String[]{"type_name"}, new int[]{R.id.item_type_name});
        type_item_list.setAdapter(adapter);
        type_item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//           Toast.makeText(MainActivity.this,type_list_data.get(i), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, PasswordListActivity.class);
                intent.putExtra("type_name", type_list_data.get(i));
                startActivity(intent);
            }
        });
        type_item_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("更改")
                        .setMessage("选择你要进行的操作")
                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击确定按钮后的操作
                                db.delete("TypeTable", "type_name=?", new String[]{type_list_data.get(i)});
                                db.delete("PasswordParameters", "type_name=?", new String[]{type_list_data.get(i)});
                                showList();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击取消按钮后的操作
                            }
                        })
                        .show();
                return true;
            }
        });
    };

    private void showList() {
        Cursor cursor = db.query("TypeTable",null,null,null,null,null,null);
        type_list_data = new ArrayList<>();
        while(cursor.moveToNext()){
            @SuppressLint("Range") String type_name = cursor.getString(cursor.getColumnIndex("type_name"));
            type_list_data.add(type_name);
            Log.i("Mainactivity","result: type_name: " + type_name);
        }
        // 关闭游标，释放资源
        cursor.close();
        List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
        for(int i = 0; i < type_list_data .size(); i++){
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("type_name", type_list_data.get(i));
            data.add(item);
        }

        SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.type_item,new String[]{"type_name"},new int[]{R.id.item_type_name});
        type_item_list.setAdapter(adapter);
        type_item_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Toast.makeText(MainActivity.this,type_list_data.get(i), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this,PasswordListActivity.class);
                intent.putExtra("type_name",type_list_data.get(i));
                startActivity(intent);
            }
        });
        type_item_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("更改")
                        .setMessage("选择你要进行的操作")
                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击确定按钮后的操作
                                db.delete("TypeTable","type_name=?",new String[]{type_list_data.get(i)});
                                db.delete("PasswordParameters","type_name=?",new String[]{type_list_data.get(i)});
                                showList();
                            }

                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击取消按钮后的操作
                            }
                        })
                        .show();

                return true;
            }
        });
    }
}